import React, { useCallback, useState, useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
import { Input, Button } from "antd";
import style from "../../style/permissionsnav.module.scss";
import { add, revise } from "../../api/addpart";
const Adddepart = () => {
  const [name, setname] = useState();
  const titletext = useRef();
  // const values = useRef();
  const id = useRef();
  const loacltion = useLocation();
  let addPartment = useCallback(async () => {
    if (loacltion.search !== "") {
      console.log(id.current);
      let result = await revise({ name, id: id.current });
      console.log(result);
      return;
    }
    let res = await add({ name });
    console.log(res);
    setname();
  }, [name, loacltion]);
  useEffect(() => {
    console.log(loacltion.search.split("="));
    titletext.current =
      loacltion.search.split("=")[loacltion.search.split("=").length - 1];
    if (loacltion.search !== "") {
      const value = loacltion.search.split("=")[1].split("&")[0];
      id.current = value;
      JSON.parse(localStorage.getItem("list")).forEach((item) => {
        if (item._id === value) {
          setname(item.name);
        }
      });
    }
    console.log(titletext);
  }, [loacltion]);
  return (
    <>
      <div className={style.add}>
        {titletext.current ? titletext.current : "添加部门"}
      </div>
      <div style={{ margin: "20px 0  0 0" }}>
        <span style={{ margin: "30px 10px 10px 40px" }}>部门名称:</span>
        <Input
          className={style.input}
          placeholder="请输入部门名称"
          value={name}
          onChange={(e) => setname(e.target.value)}
        />
      </div>
      <div className={style.btns}>
        <Button style={{ margin: "0 0 0 40px" }}>取消</Button>
        <Button style={{ margin: "0 30px" }} onClick={() => addPartment()}>
          确定
        </Button>
      </div>
    </>
  );
};

export default Adddepart;
